<template>
  <div class="user-address">
    <el-card class="address-card">
      <template #header>
        <div class="card-header">
          <span>收货地址</span>
          <el-button type="primary" @click="openAddAddressDialog"> 添加新地址 </el-button>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>

      <div v-else-if="addresses.length === 0" class="empty-container">
        <el-empty description="暂无收货地址">
          <el-button type="primary" @click="openAddAddressDialog"> 添加地址 </el-button>
        </el-empty>
      </div>

      <div v-else class="addresses-list">
        <div v-for="address in addresses" :key="address.id" class="address-item">
          <div class="address-info">
            <div class="address-header">
              <span class="receiver-name">{{ address.recipientName }}</span>
              <span class="receiver-phone">{{ address.phone }}</span>
              <el-tag v-if="address.isDefault" type="success" size="small"> 默认地址 </el-tag>
            </div>
            <div class="address-detail">
              {{ formatAddress(address) }}
            </div>
          </div>

          <div class="address-actions">
            <el-button
              v-if="!address.isDefault"
              size="small"
              @click="setDefaultAddress(address.id)"
            >
              设为默认
            </el-button>
            <el-button size="small" @click="editAddress(address)"> 编辑 </el-button>
            <el-button size="small" type="danger" @click="deleteAddress(address.id)">
              删除
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 地址编辑对话框 -->
    <el-dialog
      v-model="showAddressDialog"
      :title="editingAddress ? '编辑地址' : '添加新地址'"
      width="600px"
    >
      <el-form ref="addressFormRef" :model="addressForm" :rules="addressRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收货人" prop="recipientName">
              <el-input v-model="addressForm.recipientName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="addressForm.phone" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"
            placeholder="请选择省市区"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input
            v-model="addressForm.detailedAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>

        <el-form-item label="邮政编码" prop="postalCode">
          <el-input v-model="addressForm.postalCode" />
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault"> 设为默认收货地址 </el-checkbox>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddressDialog = false">取消</el-button>
          <el-button type="primary" @click="saveAddress" :loading="saving"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { regionData } from 'element-china-area-data'
import { AddressUtils } from '@/utils/address'
import type { Address } from '@/types/address'
import { addressService } from '@/api'
import { useAuthStore } from '@/stores'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const showAddressDialog = ref(false)
const editingAddress = ref<Address | null>(null)
const addresses = ref<Address[]>([])
const addressFormRef = ref<FormInstance>()

// 获取认证存储实例
const authStore = useAuthStore()

const openAddAddressDialog = () => {
  resetForm() // 调用重置表单的方法，这会把 editingAddress.value 设为 null
  showAddressDialog.value = true // 然后再打开对话框
}
// 地址表单
const addressForm = reactive({
  userId: authStore.user?.id,
  recipientName: '',
  phone: '',
  region: [] as string[],
  detailedAddress: '',
  postalCode: '',
  isDefault: false,
})

// 表单验证规则
const addressRules: FormRules = {
  receiverName: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
  receiverPhone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  region: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
  detailedAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
}

// 地区选项（使用完整的中国省市区数据）
const regionOptions = regionData

// 方法
const fetchAddresses = async () => {
  loading.value = true
  try {
    // 从JWT token自动获取userId，不需要手动传递
    const response = await addressService.getAddressList()
    addresses.value = response.data.data || []
    console.log('获取地址列表成功:', addresses.value)
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  } finally {
    loading.value = false
  }
}

const formatAddress = (address: Address) => {
  return AddressUtils.formatFullAddress(
    address.province,
    address.city,
    address.district,
    address.detailedAddress
  )
}

const setDefaultAddress = async (addressId: number) => {
  try {
    // TODO: 调用设置默认地址API
     console.log('设置默认地址ID:', addressId)
    await addressService.setDefaultAddress({ addressId })
   
    ElMessage.success('设置默认地址成功')
    fetchAddresses()
  } catch (error) {
    ElMessage.error('设置默认地址失败')
  }
}

const editAddress = (address: Address) => {
  editingAddress.value = address
  addressForm.recipientName = address.recipientName
  addressForm.phone = address.phone
  // 使用工具函数处理地区数据转换
  addressForm.region = AddressUtils.addressToRegionCodes({
    province: address.province,
    city: address.city,
    district: address.district
  })
  addressForm.detailedAddress = address.detailedAddress
  addressForm.postalCode = address.postalCode // 暂时注释，等待类型定义完善
  addressForm.isDefault = address.isDefault
  showAddressDialog.value = true
}

const deleteAddress = async (addressId: number) => {
  try {
    await ElMessageBox.confirm('确认删除该地址？', '删除地址', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // TODO: 调用删除地址API
    console.log('删除地址ID:', addressId)
    await addressService.deleteAddress({ addressId })

    ElMessage.success('删除地址成功')
    fetchAddresses()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除地址失败')
    }
  }
}

const saveAddress = async () => {
  if (!addressFormRef.value) return

  try {
    await addressFormRef.value.validate()
    saving.value = true

    const userId = authStore.user?.id
    if (!userId) {
      ElMessage.error('用户未登录，无法保存地址')
      return
    }

    const addressData = {
      ...addressForm,
      userId, // 确保 userId 是 number 类型
      province: addressForm.region[0],
      city: addressForm.region[1],
      district: addressForm.region[2],
    }

    if (editingAddress.value) {
      // TODO: 调用更新地址API
      await addressService.updateAddress({ id: editingAddress.value.id, ...addressData })
      ElMessage.success('地址更新成功')
    } else {
      // 修复点：确保 userId 不为 undefined
      await addressService.addAddress(addressData)
      ElMessage.success('地址添加成功')
    }

    showAddressDialog.value = false
    resetForm()
    fetchAddresses()
  } catch (error) {
    console.error('保存地址失败:', error)
    ElMessage.error('保存地址失败')
  } finally {
    saving.value = false
  }
}

const resetForm = () => {
  editingAddress.value = null
  addressForm.recipientName = ''
  addressForm.phone = ''
  addressForm.region = []
  addressForm.detailedAddress = ''
  addressForm.postalCode = ''
  addressForm.isDefault = false
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAddresses()
})
</script>

<style scoped>
.user-address {
  max-width: 800px;
  margin: 0 auto;
}

.address-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  padding: 40px 0;
}

.empty-container {
  padding: 60px 0;
}

.addresses-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.address-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  background: #fafafa;
}

.address-info {
  flex: 1;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.receiver-name {
  font-weight: 600;
  color: #303133;
}

.receiver-phone {
  color: #606266;
}

.address-detail {
  color: #606266;
  line-height: 1.6;
}

.address-actions {
  display: flex;
  gap: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .address-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .address-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .el-col {
    width: 100% !important;
  }
}
</style>
